<template>
  <el-card>
    <el-tabs v-model="activeName">
      <el-tab-pane label="基本信息" name="basic">
        <basic-info-form ref="basicInfo" :info="info" />
      </el-tab-pane>
      <el-tab-pane label="生成信息" name="genInfo">
        <gen-info-form ref="genInfo"
                       :info="info"
                       :tables="tables"
                       :menus="menus"
                       :nowFormBuildKey="formBuildKey"
                       @changeFormBuildKey="changeFormBuildKey"/>
      </el-tab-pane>
      <el-tab-pane label="表格信息" name="tableColumnInfo">
        <TableColumnInfo
          ref="tableColumnInfo"
          :formBuildKey="formBuildKey"
          :tables="tables"
          :columns="columns"
          :dictOptions="dictOptions"/>
      </el-tab-pane>
      <el-tab-pane label="按钮信息" name="btnsInfo" v-if="isShowFormBuildInfo">
        <crud-btns-config v-if="formBuildKey!=null"
                          ref="crudBtnsInfo"
                          :menuPerms="menuPerms"
                          :tableInfo="info"
                          :columns="columns"
                          :formBuildKey="formBuildKey"/>
      </el-tab-pane>
      <el-tab-pane label="表单设计" name="formBuildInfo" v-if="isShowFormBuildInfo">
        <form-build v-if="formBuildKey!=null" ref="formBuildInfo"
                    :formBuildKey="formBuildKey"
                    buildType="CRUD"
                    :tableInfo="info"
                    :tables="tables"
                    :columns="columns"
                    :menuPerms="menuPerms"
                    :dictOptions="dictOptions"/>
      </el-tab-pane>
    </el-tabs>
    <el-form label-width="100px">
      <el-form-item style="text-align: center;margin-left:-100px;margin-top:10px;">
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button @click="close()">返回</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { getGenTable, updateGenTable } from "@/api/tool/gen";
import { optionselect as getDictOptionselect } from "@/api/system/dict/type";
import { listMenu as getMenuTreeselect } from "@/api/system/menu";
import basicInfoForm from "./basicInfoForm";
import genInfoForm from "./genInfoForm";
import Sortable from 'sortablejs'
import request from "@/utils/request";

export default {
  name: "GenEdit",
  components: {
    basicInfoForm,
    genInfoForm,
    //表单设计器
    FormBuild: () => import('@/views/youshuda/components/FormBuild/index'),
    //模块按钮
    CrudBtnsConfig: () => import('@/views/youshuda/components/FormBuild/CrudBtnsConfig'),
    //表字段信息
    TableColumnInfo:()=> import('./tableColumnInfo')
  },
  data() {
    return {
      // 选中选项卡的 name
      activeName: "formBuildInfo",
      //是否显示表单配置
      isShowFormBuildInfo: false,
      // 表信息
      tables: [],
      // 表列信息
      columns: [],
      // 字典信息
      dictOptions: [],
      // 菜单信息
      menus: [],
      // 菜单权限
      menuPerms: [],
      // 表详细信息
      info: {},
      // 表单设计唯一KEY
      formBuildKey: null,
      originalFormBuildKey: null,
      originalGenType: null,
      // 字段表格当前点击的行信息
      nowColumnTableRow: null
    };
  },
  created() {
    const tableId = this.$route.params && this.$route.params.tableId;
    if (tableId) {
      //打开加载框
      this.openLoading();
      // 获取表详细信息
      getGenTable(tableId).then(res => {
        this.columns = res.data.rows;
        this.info = res.data.info;
        this.originalGenType=this.info['genType']
        // 选中选项卡的 name
        this.activeName = "tableColumnInfo"
        if(this.info['genType'] == '2'){
          //this.$route.query.buildType == "CRUD"
          this.activeName = "formBuildInfo"
          /** 初始化FormBuildKey信息 **/
          this.initFormBuildKey()
        }
        this.tables = res.data.tables;
      });
      /** 查询字典下拉列表 */
      getDictOptionselect().then(response => {
        this.dictOptions = response.data;
      });
      /** 查询菜单下拉列表 */
      getMenuTreeselect().then(response => {
        this.menus = this.handleTree(response.data, "menuId");
      });
      //关闭加载框
      this.closeLoading();
    }
  },
  methods: {
    /** 获取菜单权限 */
    getMenuPerms(menuId){
      if(this.isEmpty(menuId)){
        return;
      }
      request({
        url: 'menu/perms/'+menuId,
        method: 'get'
      }).then(res=>{
        // 菜单权限
        this.menuPerms=res.data
      })
    },
    /** 提交按钮 */
    async submitForm() {
      //表单设计信息
      let fromBuildConfig = null
      let crudBtnsInfo = null
      let clientType = ''
      let formConf = null
      if(this.info['genType'] == '2'){
        let formBuildVail = await this.$refs.formBuildInfo.vailDrawingList();
        if(!formBuildVail){
          return;
        }
        fromBuildConfig = this.$refs.formBuildInfo.drawingList;
        crudBtnsInfo = this.$refs.crudBtnsInfo.crudBtns;
        clientType = this.$refs.formBuildInfo.clientType;
        formConf = this.$refs.formBuildInfo.formConf;
      }
      const basicForm = this.$refs.basicInfo.$refs.basicInfoForm;
      const genForm = this.$refs.genInfo.$refs.genInfoForm;
      const tableConfig = this.$refs.tableColumnInfo.tableConfigInfo;

      this.openLoading();
      // 校验基本信息必填项基本信息
      const basicFormValid = await this.vailFormPromise(basicForm,"基本信息");
      // 校验生成信息必填项基本信息
      const genFormValid = await this.vailFormPromise(genForm,"生成信息");
      /** 必要校验通过后，执行保存操作 **/
      if (basicFormValid && genFormValid) {
        const genTable = Object.assign({}, basicForm.model, genForm.model);
        genTable.columns = this.columns;
        genTable.params = {
          treeCode: genTable.treeCode,
          treeName: genTable.treeName,
          treeParentCode: genTable.treeParentCode,
          parentMenuId: genTable.parentMenuId
        };
        //组装表单设计配置信息
        genTable.fromBuildConfig = fromBuildConfig;
        genTable.crudBtnsInfo = crudBtnsInfo;
        genTable.crudTableConfig = tableConfig;
        genTable.formConf = formConf;
        genTable.clientType = clientType;
        genTable.formBuildKey = this.formBuildKey;
        genTable.menuLevels = this.$route.query.levels;

        updateGenTable(genTable).then(res => {
          this.$modal.msgSuccess(res.msg);
          if (res.code === 200) {
            this.close();
          }
        }).finally(res => {
          //关闭加载框
          this.closeLoading();
        });
      } else {
        //关闭加载框
        this.closeLoading();
      }
    },
    vailFormPromise(form,formDesc) {
      return new Promise(resolve => {
        form.validate((valid, errorFields) => {
          if (!valid) {
            Object.keys(errorFields).some(key => {
              this.$modal.msgError("【"+formDesc+"】表单校验未通过【"+errorFields[key][0]['message']+"】");
              return true;
            })
          }
          resolve(valid);
        });
      });
    },
    /** 关闭按钮 */
    close() {
      let redirectPath = this.$route.query.redirect;
      if(redirectPath && this.originalGenType == this.info['genType']){
        this.$tab.closeOpenPage({ path: redirectPath, query: { t: Date.now() } });
      }else{
        const obj = { path: "/tool/gen", query: { t: Date.now(), pageNum: this.$route.query.pageNum } };
        this.$tab.closeOpenPage(obj);
        if(this.originalGenType != this.info['genType']){
          location.reload();
        }
      }
    },

    /** 初始化FormBuildKey信息 **/
    initFormBuildKey(){
      let menuId = '';
      let formBuildKey = this.$route.query.formBuildKey;
      if(this.$route.query.redirect){
        let _redirectPath = this.$route.query.redirect;
        _redirectPath=_redirectPath.substring(_redirectPath.lastIndexOf("/"))
        if(_redirectPath.indexOf("_")>-1){
          menuId = _redirectPath.split("_")[1];
          if(this.isEmpty(formBuildKey)) {
            formBuildKey = this.info['className'] + "_" + menuId;
          }
          /** 根据菜单ID获取对应菜单权限信息 */
          this.getMenuPerms(menuId)
        }
      }
      formBuildKey = formBuildKey || this.info['className']
      this.formBuildKey=formBuildKey;
      this.originalFormBuildKey=formBuildKey
    },
    /** 更新changeFormBuildKey信息 **/
    changeFormBuildKey(val){
      if(this.isEmpty(val)){
        this.formBuildKey = this.originalFormBuildKey
      }else{
        this.formBuildKey = val
      }
    }
  },
  mounted() {

  },
  watch:{
    info:{
      deep: true,
      immediate: true,
      handler:function(val, oldVal){
        this.isShowFormBuildInfo = false;
        if(val['genType'] == '2'){
          //优树搭模式，显示表单配置
          this.isShowFormBuildInfo = true;
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>

  .config-divider .el-divider__text{
    font-weight: bold !important;
  }

  .columnInfo-box{
    width: 100%;
    display: flex;

    .column-table{
      //width: 70%;
    }
    .column-config{
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: flex-start;

      .title{
        width: 100%;
        text-align: center;
        font-weight: bold;
        font-size: 13px;
        height: 43px;
        line-height: 43px;
        border-bottom: 1px solid #EBEEF5;
      }

      .column-form{
        overflow-y: scroll;
        padding: 20px 10px;
      }
    }
  }

</style>
